<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <p>用户注册</p>
    </header>
    <!-- 表单部分 -->
    <ul class="form-box">
      <li>
        <div class="title">账号：</div>
        <div class="content">
          <input
              type="text"
              @blur="checkUserId"
              v-model="user.userId"
              placeholder="账号"
          />
          <div v-if="userIdError" class="error-message">{{ userIdError }}</div>
        </div>
      </li>
      <li>
        <div class="title">密码：</div>
        <div class="content">
          <input type="password" v-model="user.password" placeholder="密码" />
          <div v-if="passwordError" class="error-message">{{ passwordError }}</div>
        </div>
      </li>
      <li>
        <div class="title">确认密码：</div>
        <div class="content">
          <input
              type="password"
              v-model="confirmPassword"
              placeholder="确认密码"
          />
          <div v-if="confirmPasswordError" class="error-message">{{ confirmPasswordError }}</div>
        </div>
      </li>
      <li>
        <div class="title">姓：</div>
        <div class="content">
          <input type="text" v-model="user.userLastName" placeholder="姓" />
          <div v-if="userLastNameError" class="error-message">{{ userLastNameError }}</div>
        </div>
      </li>
      <li>
        <div class="title">名：</div>
        <div class="content">
          <input type="text" v-model="user.userFirstName" placeholder="名" />
          <div v-if="userFirstNameError" class="error-message">{{ userFirstNameError }}</div>
        </div>
      </li>
      <li>
        <div class="title">邮箱：</div>
        <div class="content">
          <input type="text" v-model="user.userEmail" placeholder="邮箱" />
          <div v-if="userEmailError" class="error-message">{{ userEmailError }}</div>
        </div>
      </li>
      <li>
        <div class="title">电话：</div>
        <div class="content">
          <input type="text" v-model="user.userPhone" placeholder="电话" />
          <div v-if="userPhoneError" class="error-message">{{ userPhoneError }}</div>
        </div>
      </li>
      <li>
        <div class="title">性别：</div>
        <div class="content" style="font-size: 3vw">
          <input
              type="radio"
              v-model="user.userSex"
              value="1"
              style="width: 6vw; height: 3.2vw"
          />男
          <input
              type="radio"
              v-model="user.userSex"
              value="0"
              style="width: 6vw; height: 3.2vw"
          />女
        </div>
      </li>
    </ul>
    <div v-if="generalError" class="general-error">
      {{ generalError }}
    </div>
    <div class="button-login">
      <button @click="register" :disabled="loading">
        {{ loading ? '注册中...' : '注册' }}
      </button>
    </div>
    <!-- 底部菜单部分 -->
    <Footer></Footer>
  </div>
</template>

<script setup>
import {ref, reactive, watch} from 'vue'
import { useRouter } from 'vue-router'
import { userAPI } from '@/api/user.js'
import Footer from "../components/Footer.vue"

const router = useRouter()

// 响应式数据
const user = reactive({
  userId: '',
  password: '',
  userFirstName: '',
  userLastName: '',
  userEmail: '',
  userPhone: '',
  userSex: '1' // 默认男性
})

const confirmPassword = ref('')
const loading = ref(false)

// 错误信息
const userIdError = ref('')
const passwordError = ref('')
const confirmPasswordError = ref('')
const userFirstNameError = ref('')
const userLastNameError = ref('')
const userEmailError = ref('')
const userPhoneError = ref('')
const generalError = ref('')

// 验证用户名
const checkUserId = async () => {
  userIdError.value = ''

  if (!user.userId.trim()) {
    userIdError.value = '用户名不能为空'
    return false
  }

  if (user.userId.length < 3 || user.userId.length > 20) {
    userIdError.value = '用户名长度应为3-20个字符'
    return false
  }

  // 检查用户名格式（字母数字下划线）
  const usernameRegex = /^[a-zA-Z0-9_]+$/
  if (!usernameRegex.test(user.userId)) {
    userIdError.value = '用户名只能包含字母、数字和下划线'
    return false
  }

  // 检查用户名是否已存在（这里需要调用API）
  try {
    // 假设有一个检查用户名的API
    // const response = await authAPI.checkUsername(user.userId)
    // if (response.data.exists) {
    //   userIdError.value = '用户名已存在'
    //   return false
    // }
  } catch (error) {
    console.error('检查用户名失败:', error)
  }

  return true
}

// 验证密码
const validatePassword = () => {
  passwordError.value = ''

  if (!user.password) {
    passwordError.value = '密码不能为空'
    return false
  }

  if (user.password.length < 6) {
    passwordError.value = '密码长度至少6位'
    return false
  }

  // // 密码强度验证
  // const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d).{6,}$/
  // if (!passwordRegex.test(user.password)) {
  //   passwordError.value = '密码需包含字母和数字'
  //   return false
  // }

  return true
}

// 验证确认密码
const validateConfirmPassword = () => {
  confirmPasswordError.value = ''

  if (user.password !== confirmPassword.value) {
    confirmPasswordError.value = '两次输入的密码不一致'
    return false
  }

  return true
}

// // 验证用户名称
// const validateUserName = () => {
//   userNameError.value = ''
//
//   if (!user.userName.trim()) {
//     userNameError.value = '用户名称不能为空'
//     return false
//   }
//
//   if (user.userName.length < 2 || user.userName.length > 20) {
//     userNameError.value = '用户名称长度应为2-20个字符'
//     return false
//   }
//
//   return true
// }

// 表单验证
const validateForm = () => {
  let isValid = true

  // 重置错误信息
  generalError.value = ''

  if (!checkUserId()) isValid = false
  if (!validatePassword()) isValid = false
  if (!validateConfirmPassword()) isValid = false
  // if (!validateUserName()) isValid = false

  return isValid
}

// 注册逻辑
const register = async () => {
  if (!validateForm()) {
    generalError.value = '请正确填写表单信息'
    return
  }

  loading.value = true
  generalError.value = ''

  try {
    // 准备注册数据
    const registerData = {
      username: user.userId,
      password: user.password,
      firstName: user.userFirstName,
      lastName: user.userLastName,
      email: user.userEmail,
      phone: user.userPhone,
      gender: user.userSex==='1'?'男':'女',
    }

    // 调用注册API
    const response = await userAPI.register(registerData)
  console.log(response)
    if (response.data.success) {
      // 注册成功，跳转到登录页面
      alert('注册成功，请登录')
      router.push({
        path: '/login',
        query: {
          message: '注册成功，请登录'
        }
      })
    } else {
      generalError.value = response.data.message
    }

  } catch (error) {
    console.error('注册失败:', error)

    // 根据错误类型显示不同的错误信息
    if (error.response) {
      const status = error.response.status
      switch (status) {
        case 400:
          generalError.value = '请求参数错误，请检查填写的信息'
          break
        case 409:
          generalError.value = '用户名已存在，请更换其他用户名'
          break
        case 500:
          generalError.value = '服务器错误，请稍后重试'
          break
        default:
          generalError.value = '注册失败，请稍后重试'
      }
    } else if (error.request) {
      generalError.value = '网络错误，请检查网络连接'
    } else {
      generalError.value = '注册失败，请稍后重试'
    }
  } finally {
    loading.value = false
  }
}

// 实时验证
const realTimeValidation = () => {
  // 密码和确认密码的实时验证
  if (user.password && confirmPassword.value) {
    validateConfirmPassword()
  }
}

// 监听相关字段的变化进行实时验证
watch(() => user.password, realTimeValidation)
watch(() => confirmPassword.value, realTimeValidation)
</script>

<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  height: 100%;
}
/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}
/****************** 表单部分 ******************/
.wrapper .form-box {
  width: 100%;
  margin-top: 12vw;
}
.wrapper .form-box li {
  box-sizing: border-box;
  padding: 4vw 3vw 0 3vw;
  display: flex;
  align-items: center;
}
.wrapper .form-box li .title {
  flex: 0 0 18vw;
  font-size: 3vw;
  font-weight: 700;
  color: #666;
}
.wrapper .form-box li .content {
  flex: 1;
}
.wrapper .form-box li .content input {
  border: none;
  outline: none;
  width: 100%;
  height: 4vw;
  font-size: 3vw;
}

/* 错误信息样式 */
.error-message {
  color: #ff4757;
  font-size: 2.8vw;
  margin-top: 1vw;
  height: 3vw;
}

.general-error {
  color: #ff4757;
  font-size: 3vw;
  text-align: center;
  margin: 2vw 3vw;
  padding: 2vw;
  background-color: #ffe6e6;
  border-radius: 4px;
  border-left: 4px solid #ff4757;
}

.wrapper .button-login {
  width: 100%;
  box-sizing: border-box;
  padding: 4vw 3vw 0 3vw;
}
.wrapper .button-login button {
  width: 100%;
  height: 10vw;
  font-size: 3.8vw;
  font-weight: 700;
  color: #fff;
  background-color: #38ca73;
  border-radius: 4px;
  border: none;
  outline: none;
}

.wrapper .button-login button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.wrapper .button-register {
  width: 100%;
  box-sizing: border-box;
  padding: 4vw 3vw 0 3vw;
}
.wrapper .button-register button {
  width: 100%;
  height: 10vw;
  font-size: 3.8vw;
  font-weight: 700;
  color: #666;
  background-color: #eee;
  border-radius: 4px;
  border: none;
  outline: none;
  border: solid 1px #ddd;
}
</style>